package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.PageResult;
import com.itheima.domain.PmsProduct;
import com.itheima.domain.SmsFlashPromotionProductRelation;
import com.itheima.mapper.PmsProductMapper;
import com.itheima.mapper.SmsFlashPromotionProductRelationMapper;
import com.itheima.service.SmsFlashPromotionProductRelationService;
import com.itheima.vo.ProductRelationVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品限时购与商品关系表 服务实现类
 * </p>
 *
 * @author zhuguo
 * @since 2022-11-10
 */
@DubboService
public class SmsFlashPromotionProductRelationServiceImpl extends ServiceImpl<SmsFlashPromotionProductRelationMapper, SmsFlashPromotionProductRelation> implements SmsFlashPromotionProductRelationService {

    @Autowired
    PmsProductMapper pmsProductMapper;
    @Override
    public PageResult pageList(Integer flashPromotionId, Integer flashPromotionSessionId, Integer pageNum, Integer pageSize) {
        Page<SmsFlashPromotionProductRelation> page = new Page<>(pageNum,pageSize);
        Page<ProductRelationVo> pageVo = new Page<>();
        //查询关系表中id符合条件的数据
        LambdaQueryWrapper<SmsFlashPromotionProductRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SmsFlashPromotionProductRelation::getFlashPromotionId,flashPromotionId);
        queryWrapper.eq(SmsFlashPromotionProductRelation::getFlashPromotionSessionId,flashPromotionSessionId);
        this.page(page,queryWrapper);
        BeanUtil.copyProperties(page,pageVo);
        List<SmsFlashPromotionProductRelation> records = page.getRecords();
        //新建一个集合用于封装vo
        List<ProductRelationVo> list = new ArrayList<>();
        for (SmsFlashPromotionProductRelation productRelation : records) {
            ProductRelationVo productRelationVo = new ProductRelationVo();
            BeanUtil.copyProperties(productRelation,productRelationVo);
            //根据商品id获取商品信息
            PmsProduct product = pmsProductMapper.selectById(productRelation.getProductId());
            productRelationVo.setProduct(product);
            list.add(productRelationVo);
        }
        pageVo.setRecords(list);
        return new PageResult(pageNum,pageSize,page.getTotal(),page.getPages(),pageVo.getRecords());

    }
}
